package com.mlnx.work.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mlnx.common.utils.MyLog;
import com.mlnx.work.entity.User;
import com.mlnx.work.exception.WorkServiceException;
import com.mlnx.work.service.UserService;

import org.apache.commons.lang3.StringUtils;
import org.shan.security.app.authorize.AppAuthorizeManager;
import org.shan.security.app.authorize.MlnxOauthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Created by amanda.shan on 2019/6/20.
 */
@Component
public class WorkAuthorizeManager implements AppAuthorizeManager {

    MyLog log = MyLog.getLog(getClass());

    @Autowired
    private PasswordEncoder encoder;

    @Autowired
    private UserService userService;

    @Override
    public MlnxOauthUser authenticate(Map<String, String> requestParameters, ClientDetails authenticatedClient) {

        String grantType = requestParameters.get(OAuth2Utils.GRANT_TYPE);

        // 刷新Token不需要添加用户名密码
        if (grantType.equals("refresh_token")) {
            return null;
        }

        // 管理员登入
        String username = requestParameters.get("username");
        String password = requestParameters.get("password");


        // 根据获取用户信息
        User user = null;

        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            user = userService.getOne(new QueryWrapper<User>().eq("username", username));
            if (user == null || !encoder.matches(password, user.getPswd())) {
                throw new WorkServiceException("用户名密码错误");
            }
        } else {
            throw new WorkServiceException("用户名密码不能为空");
        }

        if (user != null) {
            password = user.getPswd();
            if (StringUtils.isEmpty(password)) {
                password = "123456";
            }
            return new MlnxOauthUser(user.getUsername(), password);
        } else {
            throw new WorkServiceException("用户名密码错误");
        }

    }
}
